package com.davies.learn.flux.configuration.routes;

import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static org.springframework.http.MediaType.ALL;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;

/**
 * @author davies
 * @date 2023/8/10 11:29
 */
@Log
@Component
public class HelloRouter {

    private final WebClient webClient;

    public HelloRouter(WebClient webClient) {
        this.webClient = webClient;
    }

    @Bean
    public RouterFunction<ServerResponse> routerFunction() {
        return RouterFunctions
                .route()
                .GET("/", accept(ALL), this::hello)
                .build();
    }

    private Mono<ServerResponse> hello(ServerRequest request) {
        Mono<String> stringMono = this.webClient.get().uri("http://localhost:3000/api")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .retrieve()
                .bodyToMono(String.class);
        String beginTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Mono<String> body = stringMono.map(time -> beginTime + "  " + time);
        return ServerResponse.ok().contentType(APPLICATION_JSON)
                .body(body, String.class);

    }
}
